﻿using NXDO.Data.Extension;
using NXDO.Data.Factory;
using TDM.WebBiz.Common;
using TDM.DbData.DataEntity;
using TDM.WebBase;

namespace TDM.WebBiz.TestData
{
    public class TestResultFileHelper
    {
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="fileIDs"></param>
        public static void DeleteFile(List<long> fileIDs)
        {
            foreach (var fileID in fileIDs)
            {
                string basePath = BasePathHelper.GetProjectBasePath();
                TestResultFile file = Get(fileID);
                var filePath = Path.Combine(basePath, file.StorePath, fileID.ToString() + file.FileExtension);
                try
                {
                    File.Delete(filePath);
                }
                catch (Exception) { }
                file.isDelete = true;
                file.DBLinq().ToCommand(file).Update();
            }
        }

        public static MemoryStream DownloadTestResFile(List<long> fileIDs)
        {
            try
            {
                Dictionary<string, List<FileData>> filesdic = new Dictionary<string, List<FileData>>();
                List<FileData> files = new List<FileData>();
                foreach (var fileID in fileIDs)
                {
                    string basePath = BasePathHelper.GetProjectBasePath();
                    TestResultFile file = Get(fileID);
                    var filePath = Path.Combine(basePath, file.StorePath, fileID.ToString() + file.FileExtension);
                    string dirtype = EnumExtension.GetDescription((ResultFileType)file.FileType);
                    if (filesdic.ContainsKey(dirtype))
                    {
                        filesdic[dirtype].Add(new FileData
                        {
                            FileName = file.FileName,
                            Content = File.ReadAllBytes(filePath)
                        });
                    }
                    else
                    {
                        filesdic.Add(dirtype, new List<FileData>
                        {
                            new FileData
                            {
                                FileName = file.FileName,
                                Content = File.ReadAllBytes(filePath)
                            }
                        });
                    }
                }
                return ZipFileHelper.CreateZippedStream(filesdic);
            }
            catch (Exception)
            {

                throw;
            }

        }

        public static TestResultFile Get(long fileID)
        {
            var sql = $"select * from TestResultFile where  TDFID = {fileID}";
            var rs = DbHelper.SetCommand(sql).ExecuteEntityScalar<TestResultFile>();
            return rs;
        }
    }
}
